package com.cc.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtil {
    //线程安全的容器
    public static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    public static SqlSession openSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession==null){
            String resource = "mybatis-config.xml";
            InputStream inputStream = null;
            try {
                inputStream = Resources.getResourceAsStream(resource);
            } catch (IOException e) {
                e.printStackTrace();
            }
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession = sqlSessionFactory.openSession();
            threadLocal.set(sqlSession);
        }
        return  sqlSession;
    }
    public static void close(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession!=null){
            sqlSession.close();
        }
    }
}
